import {defineStore} from 'pinia'

import router from "@/router";
import {localCache} from "@/utils";
import zjRequest from "@/services";
import {IResponseData} from "@/services/types";
import {IActions, IState, URL_TYPE} from "@/store/accountModule/types";

export const setupAccount = () => {
    const accountStore = useAccountStore()
    let userInfo = localCache.getCache("userInfo")
    if (userInfo) {
        accountStore.setUserInfoAction(userInfo)
    }
}
const useAccountStore = defineStore<any, IState, any, IActions>('accountModule', {
    state: () => {
        return {
            userInfo: {
                id: 0,
                username: "",
                permission: {
                    key: 1,
                    label: ""
                },
                avatar_url: ""
            },
        }
    },
    actions: {
        async resetAccountAction() {
            localCache.setCache("userInfo", "")
            this.userInfo = {
                id: 0,
                username: "",
                permission: {
                    key: 1,
                    label: ""
                },
                avatar_url: ""
            }
            router.replace("/login")
        },
        async logoutAction() {
            zjRequest.post({
                url: URL_TYPE.ACCOUNT_LOGOUT
            })
            this.resetAccountAction()
        },
        setUserInfoAction(userInfo) {
            this.userInfo = userInfo
            localCache.setCache("userInfo", this.userInfo)
        },
        async accountLoginAction(params) {
            const res: IResponseData = await zjRequest.post({
                url: URL_TYPE.ACCOUNT_LOGIN,
                data: params
            })
            if (res.code === 0) {
                this.setUserInfoAction(res.data)
                router.push("/home")
            }
        }
    }
})
export default useAccountStore
